package com.zhixing.service.processor;

import com.zhixing.common.ISwaggerConstants;
import com.zhixing.model.SwaggerResponse;
import lombok.Getter;

import java.io.IOException;
import java.util.*;

/**
 * swagger 响应码 json 解析处理器
 * @author zhixing
 */
public class SwaggerResponseCodeProcessor implements SwaggerProcessor{
    /** json 解析后的 入参对象 **/
    @Getter
    private List<SwaggerResponse>   resultList;

    @Getter
    private Map<String, Object>     responses;

    private SwaggerResponseCodeProcessor(){
        this.resultList = new ArrayList<>();
    }

    public static Builder createBuild(){
        return  new Builder();
    }

    public static class Builder{
        private SwaggerResponseCodeProcessor processor;
        public Builder(){
            this.processor = new SwaggerResponseCodeProcessor();
        }

        public Builder responses(Map<String, Object> responses){
            this.processor.responses = responses;
            return this;
        }

        public SwaggerResponseCodeProcessor build(){
            return this.processor;
        }

    }

    @Override
    public SwaggerResponseCodeProcessor process() throws IOException {
        doProcess();
        return this;
    }

    /**
     * 处理参数列表
     *
     * @return
     */
    private void doProcess() {
        Iterator<Map.Entry<String, Object>> resIt = responses.entrySet().iterator();
        while (resIt.hasNext()) {
            Map.Entry<String, Object> entry = resIt.next();
            SwaggerResponse response = new SwaggerResponse();
            // 状态码 200 201 401 403 404 这样
            response.setName(entry.getKey());
            LinkedHashMap<String, Object> statusCodeInfo = (LinkedHashMap) entry.getValue();
            response.setDescription(String.valueOf(statusCodeInfo.get(ISwaggerConstants.IPATHS.IRESPONSE.DESC)));
            Object schema = statusCodeInfo.get(ISwaggerConstants.IPATHS.SCHEMA);

            if (schema != null) {
                Object originalRef = ((LinkedHashMap) schema).get(ISwaggerConstants.IPATHS.IRESPONSE.ORIGINAL_REF);
                response.setRemark(originalRef == null ? "" : originalRef.toString());
            }
            resultList.add(response);
        }
    }
}
